<template>
  <div class="clue-container">
    <!-- 搜索筛选区域 -->
    <div class="search-filter">
      <div class="filter-row">
        <el-input v-model.number="searchForm.clueId" placeholder="线索ID" clearable class="search-input" type="number" />
        <el-input v-model="searchForm.phone" placeholder="手机号" clearable class="search-input" />
        <el-select v-model.number="searchForm.status" placeholder="线索状态" clearable class="search-select">
          <el-option label="请选择" value="" />
          <el-option label="待分配" value="1" />
          <el-option label="跟进中" value="2" />
          <el-option label="已转商机" value="3" />
        </el-select>
        <el-select v-model.number="searchForm.channel" placeholder="线索来源" clearable class="search-select">
          <el-option label="请选择" value="" />
          <el-option label="线上活动" value="1" />
          <el-option label="推广介绍" value="2" />
        </el-select>
        <el-input v-model="searchForm.assignName" placeholder="归属人姓名" clearable class="search-input" />
        <el-button type="primary" @click="search" class="search-btn">搜索</el-button>
        <el-button @click="reset" class="reset-btn">重置</el-button>
      </div>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="addClue" class="add-btn">新建线索</el-button>
    </div>

    <!-- 线索列表表格 -->
    <div class="clue-table-wrapper">
      <el-table
        v-loading="loading"
        :data="clueList"
        stripe
        style="width: 100%"
        row-key="id"
      >
        <el-table-column prop="id" label="线索ID" width="100" align="center" />
        <el-table-column prop="phone" label="手机号" width="180" align="center" />
        <el-table-column prop="name" label="客户姓名" min-width="150" align="center" />
        <el-table-column prop="channel" label="线索来源" width="120" align="center">
          <template #default="scope">
            {{ getChannelText(scope.row.channel) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="assignName" label="归属人" min-width="150" align="center" />
        <el-table-column prop="nextTime" label="下次跟进时间" min-width="180" align="center" />
        <el-table-column prop="createTime" label="创建时间" min-width="180" align="center" />
        <el-table-column label="操作" min-width="250" align="center">
          <template #default="scope">
            <!-- 管理员角色 - 使用roleLabel -->
            <template v-if="currentUser.roleLabel === 'admin' || currentUser.roleLabel === 'Super-admin'">
              <el-button size="small" type="success" @click="assignClue(scope.row)">分配</el-button>
            </template>
            
            <!-- 线索专员角色 - 使用roleLabel 并且是该线索的归属人 -->
            <template v-else-if="currentUser.roleLabel === 'clue_operator' && scope.row.assignName === currentUser.name">
              <el-button size="small" type="primary" @click="followClue(scope.row)">跟进</el-button>
              <el-button size="small" type="warning" @click="convertToBusiness(scope.row)">转商机</el-button>
              <el-button size="small" type="danger" @click="handleFalseClue(scope.row)">伪线索</el-button>
            </template>
            
            <!-- 商机专员角色 并且是该线索的归属人 -->
            <template v-else-if="currentUser.roleLabel === 'business_operat' && scope.row.assignName === currentUser.name">
              <el-button size="small" type="primary" @click="followClue(scope.row)">跟进</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <div class="total-info">共 {{ pagination.total }} 条记录 第 {{ pagination.currentPage }} / {{ Math.ceil(pagination.total / pagination.pageSize) }} 页</div>
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50]"
        layout="prev, pager, next"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <div class="page-size-select">
        <span>{{ pagination.pageSize }}条/页</span>
        <el-select
          v-model="pagination.pageSize"
          @change="handleSizeChange"
          class="page-size-select-inner"
        >
          <el-option
            v-for="size in [10, 20, 50]"
            :key="size"
            :label="size + '条/页'"
            :value="size"
          />
        </el-select>
      </div>
      <div class="jump-to">
        <span>跳至</span>
        <el-input
          v-model.number="jumpPage"
          type="number"
          :min="1"
          :max="Math.ceil(pagination.total / pagination.pageSize)"
          class="jump-input"
          @change="jumpToPage"
        />
        <span>页</span>
      </div>
    </div>

    <!-- 线索添加对话框 -->
    <el-dialog
      v-model="dialogFormVisible"
      title="添加线索"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="dialogFormRef"
        :model="dialogForm"
        :rules="dialogRules"
        label-width="80px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户姓名" prop="name">
              <el-input v-model="dialogForm.name" placeholder="请输入客户姓名" />
            </el-form-item>
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="dialogForm.phone" placeholder="请输入手机号码" />
            </el-form-item>
            <el-form-item label="线索来源" prop="channel">
              <el-select v-model.number="dialogForm.channel" placeholder="请选择线索来源">
                <el-option label="线上活动" value="1" />
                <el-option label="推广介绍" value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="关联活动ID" prop="activityId">
              <el-input v-model.number="dialogForm.activityId" placeholder="无关联活动可留空" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model.number="dialogForm.gender" placeholder="请选择性别">
                <el-option label="男" value="1" />
                <el-option label="女" value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="年龄" prop="age">
              <el-input v-model.number="dialogForm.age" placeholder="请输入年龄" type="number" />
            </el-form-item>
            <el-form-item label="微信号" prop="wechat">
              <el-input v-model="dialogForm.wechat" placeholder="请输入微信号" />
            </el-form-item>
            <el-form-item label="QQ号" prop="qq">
              <el-input v-model="dialogForm.qq" placeholder="请输入QQ号" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 线索详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="线索详情"
      width="800px"
      @close="handleDetailDialogClose"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="detail-item">
            <label>线索ID：</label>
            <span>{{ detailClue.id || '-' }}</span>
          </div>
          <div class="detail-item">
            <label>客户姓名：</label>
            <span>{{ detailClue.name || '-' }}</span>
          </div>
          <div class="detail-item">
            <label>手机号：</label>
            <span>{{ detailClue.phone || '-' }}</span>
          </div>
          <div class="detail-item">
            <label>线索来源：</label>
            <span>{{ detailClue.channel ? getChannelText(detailClue.channel) : '-' }}</span>
          </div>
          <div class="detail-item">
            <label>关联活动ID：</label>
            <span>{{ detailClue.activityId || '-' }}</span>
          </div>
          <div class="detail-item">
            <label>性别：</label>
            <span>{{ detailClue.gender ? (detailClue.gender === 1 ? '男' : '女') : '-' }}</span>
          </div>
          <div class="detail-item">
            <label>年龄：</label>
            <span>{{ detailClue.age || '-' }}</span>
          </div>
          <div class="detail-item">
            <label>微信号：</label>
            <span>{{ detailClue.wechat || '-' }}</span>
          </div>
          <div class="detail-item">
            <label>QQ号：</label>
            <span>{{ detailClue.qq || '-' }}</span>
          </div>
          <div class="detail-item">
            <label>归属人：</label>
            <span>{{ detailClue.assignName || '-' }}</span>
          </div>
          <div class="detail-item">
            <label>状态：</label>
            <el-tag :type="detailClue.status ? getStatusType(detailClue.status) : 'default'">
              {{ detailClue.status ? getStatusText(detailClue.status) : '-' }}
            </el-tag>
          </div>
          <div class="detail-item">
            <label>下次跟进时间：</label>
            <span>{{ detailClue.nextTime || '-' }}</span>
          </div>
        </el-col>
      </el-row>
      
      <!-- 跟进记录 -->
      <div class="track-records">
        <h4>跟进记录</h4>
        <el-empty v-if="trackRecords.length === 0" description="暂无跟进记录" />
        <div v-else class="record-list">
          <div v-for="record in trackRecords" :key="record.id" class="record-item">
            <div class="record-header">
              <span class="record-user">{{ record.assignName || '系统' }}</span>
              <span class="record-time">{{ record.createTime }}</span>
            </div>
            <div class="record-content">{{ record.record }}</div>
            <div v-if="record.nextTime" class="record-next">
              下次跟进时间：{{ record.nextTime }}
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
    
    <!-- 跟进线索对话框 -->
    <el-dialog
      v-model="followDialogVisible"
      :title="`跟进线索(线索ID:${followForm.id})`"
      width="800px"
      @close="handleFollowDialogClose"
    >
      <el-form
        ref="followFormRef"
        :model="followForm"
        :rules="followRules"
        label-width="100px"
      >
        <!-- 客户基本信息 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="* 手机号码" prop="phone">
              <el-input v-model="followForm.phone" placeholder="请输入手机号码" disabled />
            </el-form-item>
            <el-form-item label="* 渠道来源" prop="channel">
              <el-select v-model="followForm.channel" placeholder="请选择渠道来源" disabled>
                <el-option label="线上活动" value="线上活动" />
                <el-option label="推广介绍" value="推广介绍" />
              </el-select>
            </el-form-item>
            <el-form-item label="活动信息" prop="activityInfo">
              <el-select v-model="followForm.activityInfo" placeholder="请选择活动信息">
                <el-option label="Java课程折扣活动" value="Java课程折扣活动" />
                <el-option label="Python入门讲座" value="Python入门讲座" />
              </el-select>
            </el-form-item>
            <el-form-item label="客户姓名" prop="name">
              <el-input v-model="followForm.name" placeholder="请输入客户姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="followForm.gender" placeholder="请选择性别">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
              </el-select>
            </el-form-item>
            <el-form-item label="年龄" prop="age">
              <el-input v-model="followForm.age" placeholder="请输入年龄" />
            </el-form-item>
            <el-form-item label="微信号" prop="wechat">
              <el-input v-model="followForm.wechat" placeholder="请输入微信号" />
            </el-form-item>
            <el-form-item label="QQ号" prop="qq">
              <el-input v-model="followForm.qq" placeholder="请输入QQ号" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 意向信息 -->
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="12">
            <el-form-item label="* 意向学科" prop="intentionSubject">
              <el-select v-model="followForm.intentionSubject" placeholder="请选择意向学科" style="width: 100%">
                <el-option
                  v-for="option in intentionSubjectOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="* 意向等级" prop="intentionLevel">
              <el-select v-model="followForm.intentionLevel" placeholder="请选择意向等级" style="width: 100%">
                <el-option
                  v-for="option in intentionLevelOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="24">
            <el-form-item label="* 下次跟进时间" prop="nextTime">
              <el-date-picker
                v-model="followForm.nextTime"
                type="datetime"
                placeholder="选择下次跟进时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="24">
            <el-form-item label="* 跟进记录" prop="record">
              <el-input
                v-model="followForm.record"
                type="textarea"
                rows="4"
                placeholder="请输入跟进记录"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 跟进历史表格 -->
        <el-row style="margin-top: 20px;">
          <el-col :span="24">
            <h4 style="margin-bottom: 10px;">跟进历史</h4>
            <el-table :data="trackRecords" style="width: 100%;" size="small">
              <el-table-column prop="intentionLevel" label="意向等级" min-width="120" />
              <el-table-column prop="intentionSubject" label="意向学科" min-width="180" />
              <el-table-column prop="createBy" label="跟进人" min-width="100" />
              <el-table-column prop="createTime" label="跟进时间" min-width="180" />
              <el-table-column prop="nextTime" label="下次跟进时间" min-width="180" />
              <el-table-column prop="record" label="跟进记录" min-width="200" />
            </el-table>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="handleFollowDialogClose">取消</el-button>
        <el-button type="primary" @click="submitFollow">确定</el-button>
      </template>
    </el-dialog>

    <!-- 线索上报对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="线索上报"
      width="400px"
      @close="handleImportDialogClose"
    >
      <el-upload
        class="upload-demo"
        drag
        action=""
        :on-change="handleFileChange"
        :auto-upload="false"
        :limit="1"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">拖放文件到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">
            请上传Excel格式的线索文件，文件大小不超过2MB
          </div>
        </template>
      </el-upload>
      <template #footer>
        <el-button @click="handleImportDialogClose">取消</el-button>
        <el-button type="primary" @click="submitImport">确定上传</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown, UploadFilled } from '@element-plus/icons-vue'
import axios from 'axios'

// 创建axios实例并添加请求拦截器
// 配置baseURL为'/api'，这样请求会经过vite的代理转发到后端
const api = axios.create({
  baseURL: '/api'
})

// 请求拦截器 - 添加token认证头
api.interceptors.request.use(config => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.token = token
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 响应式数据
const loading = ref(false)
const clueList = ref([])
const searchForm = reactive({
  clueId: '',
  phone: '',
  status: '',
  channel: '',
  assignName: ''
})

// 从localStorage获取用户信息
const currentUser = ref({})

// 初始化时获取用户信息
onMounted(() => {
  const userInfo = localStorage.getItem('user')
  if (userInfo) {
    currentUser.value = JSON.parse(userInfo)
  }
  loadClueList()
})
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const jumpPage = ref(1)

const jumpToPage = () => {
  if (jumpPage.value && jumpPage.value >= 1 && jumpPage.value <= Math.ceil(pagination.total / pagination.pageSize)) {
    pagination.currentPage = jumpPage.value
    loadClueList()
  } else {
    ElMessage.warning('请输入有效的页码')
    jumpPage.value = pagination.currentPage
  }
}

// 对话框相关
const dialogFormVisible = ref(false)
const importDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const followDialogVisible = ref(false)

const dialogForm = reactive({
  phone: '',
  channel: '',
  activityId: null,
  name: '',
  gender: '',
  age: '',
  wechat: '',
  qq: ''
})

const dialogRules = {
  phone: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
  channel: [{ required: true, message: '请选择线索来源', trigger: 'blur' }],
  name: [{ required: true, message: '请输入客户姓名', trigger: 'blur' }]
}

// 详情相关数据
const detailClue = reactive({})
const trackRecords = ref([])

// 跟进相关数据
const followForm = reactive({
  id: '',
  record: '',
  nextTime: '',
  intentionSubject: '',
  intentionLevel: '',
  phone: '',
  channel: '',
  activityInfo: '',
  name: '',
  gender: '',
  age: '',
  wechat: '',
  qq: ''
})

// 意向学科选项
const intentionSubjectOptions = [
  { label: 'Java后端开发', value: 'Java后端开发' },
  { label: '前端开发', value: '前端开发' },
  { label: 'Python', value: 'Python' },
  { label: '测试开发', value: '测试开发' },
  { label: '数据结构/算法', value: '数据结构/算法' },
  { label: '数据库', value: '数据库' },
  { label: '网络安全', value: '网络安全' },
  { label: '运维', value: '运维' },
  { label: '大数据', value: '大数据' },
  { label: '人工智能', value: '人工智能' },
  { label: '区块链', value: '区块链' },
  { label: '云计算', value: '云计算' },
  { label: '其他', value: '其他' }
]

// 意向等级选项
const intentionLevelOptions = [
  { label: '了解', value: '了解' },
  { label: '考虑中', value: '考虑中' },
  { label: '计划报名', value: '计划报名' },
  { label: '犹豫', value: '犹豫' },
  { label: '暂时不考虑', value: '暂时不考虑' },
  { label: '确定不报名', value: '确定不报名' }
]

const followRules = {
  record: [{ required: true, message: '请输入跟进记录', trigger: 'blur' }],
  nextTime: [{ required: true, message: '请选择下次跟进时间', trigger: 'change' }],
  intentionSubject: [{ required: true, message: '请选择意向学科', trigger: 'change' }],
  intentionLevel: [{ required: true, message: '请选择意向等级', trigger: 'change' }]
}
const dialogFormRef = ref()
const followFormRef = ref()

// 状态文本映射
const getStatusText = (status) => {
  const statusMap = {
    1: '待分配',
    2: '跟进中',
    3: '已转商机'
  }
  return statusMap[status] || '未知'
}

// 状态类型映射
const getStatusType = (status) => {
  const typeMap = {
    1: 'info',
    2: 'primary',
    3: 'success'
  }
  return typeMap[status] || 'default'
}

// 渠道文本映射
const getChannelText = (channel) => {
  const channelMap = {
    1: '线上活动',
    2: '推广介绍'
  }
  return channelMap[channel] || '未知'
}

// 生命周期 - 已移至用户信息初始化部分

// 方法
const loadClueList = async () => {
  loading.value = true
  try {
    // 同步jumpPage的值
    jumpPage.value = pagination.currentPage
    // 构建查询参数
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize
    }
    
    // 只添加非空的查询条件
    if (searchForm.clueId) params.clueId = searchForm.clueId
    if (searchForm.phone) params.phone = searchForm.phone
    if (searchForm.status) params.status = searchForm.status
    if (searchForm.channel) params.channel = searchForm.channel
    if (searchForm.assignName) params.assignName = searchForm.assignName
    
    // 调用真实API
    const response = await api.get('/clues', { params })
    
    if (response.data.code === 1) {
      clueList.value = response.data.data.rows
      pagination.total = response.data.data.total
    } else {
      ElMessage.error(response.data.msg || '获取线索列表失败')
    }
  } catch (error) {
    console.error('获取线索列表出错:', error)
    ElMessage.error('获取线索列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const search = () => {
  // 重置页码
  pagination.currentPage = 1
  // 执行搜索逻辑
  loadClueList()
}

const reset = () => {
  // 清空搜索条件
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  // 重置页码
  pagination.currentPage = 1
  // 重新加载数据
  loadClueList()
}

const addClue = () => {
  // 重置表单
  Object.keys(dialogForm).forEach(key => {
    dialogForm[key] = ''
  })
  // 显示对话框
  dialogFormVisible.value = true
}

const importClue = () => {
  importDialogVisible.value = true
}

const viewClue = async (row) => {
  try {
    loading.value = true
    
    // 调用根据ID查询线索接口
    const response = await api.get(`/clues/${row.id}`)
    
    if (response.data.code === 1) {
      // 清空之前的数据
      Object.keys(detailClue).forEach(key => delete detailClue[key])
      
      // 设置详情数据
      Object.assign(detailClue, response.data.data)
      // 设置跟进记录
      trackRecords.value = response.data.data.trackRecords || []
      
      // 显示详情对话框
      detailDialogVisible.value = true
    } else {
      ElMessage.error(response.data.msg || '获取线索详情失败')
    }
  } catch (error) {
    console.error('获取线索详情出错:', error)
    ElMessage.error('获取线索详情失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const followClue = async (row) => {
  try {
    loading.value = true
    
    // 设置线索ID
    followForm.id = row.id
    // 清空其他表单数据
    followForm.record = ''
    followForm.nextTime = ''
    followForm.intentionSubject = ''
    followForm.intentionLevel = ''
    
    // 调用根据ID查询线索接口获取详细信息
    const response = await api.get(`/clues/${row.id}`)
    
    if (response.data.code === 1) {
      const clueData = response.data.data
      
      // 填充表单数据
      followForm.phone = clueData.phone || ''
      followForm.channel = getChannelText(clueData.channel) || ''
      followForm.name = clueData.name || ''
      followForm.gender = clueData.gender === 1 ? '男' : clueData.gender === 2 ? '女' : ''
      followForm.age = clueData.age || ''
      followForm.wechat = clueData.wechat || ''
      followForm.qq = clueData.qq || ''
      followForm.nextTime = clueData.nextTime || ''
      
      // 设置跟进记录
      trackRecords.value = clueData.trackRecords || []
    } else {
      ElMessage.error(response.data.msg || '获取线索详情失败')
    }
    
    // 显示跟进对话框
    followDialogVisible.value = true
  } catch (error) {
    console.error('获取线索详情出错:', error)
    ElMessage.error('获取线索详情失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const assignClue = async (row) => {
  try {
    // 模拟选择用户ID（实际应用中应打开选择用户的对话框）
    const userId = prompt('请输入要分配给的用户ID:')
    
    if (!userId || isNaN(userId)) {
      ElMessage.warning('请输入有效的用户ID')
      return
    }
    
    loading.value = true
    
    // 调用分配线索API
    const response = await api.put(`/clues/assign/${row.id}/${userId}`)
    
    if (response.data.code === 1) {
      ElMessage.success('线索分配成功')
      loadClueList()
    } else {
      ElMessage.error(response.data.msg || '线索分配失败')
    }
  } catch (error) {
    console.error('分配线索出错:', error)
    ElMessage.error('线索分配失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 转商机功能
const convertToBusiness = async (row) => {
  try {
    ElMessageBox.confirm(
      '确定要将该线索转为商机吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(async () => {
      loading.value = true
      
      // 调用转商机接口
      const response = await api.put(`/clues/toBusiness/${row.id}`)
      
      if (response.data.code === 1) {
        ElMessage.success('线索转商机成功')
        loadClueList()
      } else {
        ElMessage.error(response.data.msg || '线索转商机失败')
      }
    }).catch(() => {
      // 取消操作
    })
  } catch (error) {
    console.error('线索转商机出错:', error)
    ElMessage.error('线索转商机失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 伪线索原因选项
const falseClueReasons = [
  { label: '空号', value: 1 },
  { label: '电话停机', value: 2 },
  { label: '号码错误', value: 3 },
  { label: '非目标客户', value: 4 },
  { label: '其他原因', value: 5 }
]

const handleFalseClue = async (row) => {
  try {
    // 选择伪线索原因
    const reason = prompt('请选择伪线索原因：\n1. 空号\n2. 电话停机\n3. 号码错误\n4. 非目标客户\n5. 其他原因')
    
    if (!reason || isNaN(reason) || reason < 1 || reason > 5) {
      ElMessage.warning('请选择有效的伪线索原因')
      return
    }
    
    const remark = prompt('请输入备注说明（可选）：')
    
    loading.value = true
    
    // 构建请求体
    const requestData = {
      reason: Number(reason)
    }
    if (remark) {
      requestData.remark = remark
    }
    
    // 调用伪线索处理API
    const response = await api.put(`/clues/false/${row.id}`, requestData)
    
    if (response.data.code === 1) {
      ElMessage.success('标记为伪线索成功')
      loadClueList()
    } else {
      ElMessage.error(response.data.msg || '标记为伪线索失败')
    }
  } catch (error) {
    console.error('伪线索处理出错:', error)
    ElMessage.error('标记为伪线索失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const markAsFake = (row) => {
  ElMessageBox.confirm(
    '确定要将该线索标记为伪线索吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('标记成功')
  }).catch(() => {
    // 取消操作
  })
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadClueList()
}

const handleCurrentChange = (current) => {
  pagination.currentPage = current
  loadClueList()
}

const handleDialogClose = () => {
  dialogFormVisible.value = false
  if (dialogFormRef.value) {
    dialogFormRef.value.resetFields()
  }
}

const handleImportDialogClose = () => {
  importDialogVisible.value = false
}

const handleDetailDialogClose = () => {
  detailDialogVisible.value = false
  // 清空详情数据
  Object.keys(detailClue).forEach(key => delete detailClue[key])
  trackRecords.value = []
}

const handleFollowDialogClose = () => {
  followDialogVisible.value = false
  // 重置表单
  if (followFormRef.value) {
    followFormRef.value.resetFields()
  }
  followForm.id = ''
  followForm.record = ''
  followForm.nextTime = ''
}

const submitForm = async () => {
  try {
    await dialogFormRef.value.validate()
    loading.value = true
    
    // 构建请求数据，只包含非空字段
    const requestData = {}
    for (const [key, value] of Object.entries(dialogForm)) {
      if (value !== '' && value !== null && value !== undefined) {
        // 确保数字类型的字段正确转换
        if (key === 'channel' || key === 'activityId' || key === 'gender' || key === 'age') {
          requestData[key] = value === '' ? null : Number(value)
        } else {
          requestData[key] = value
        }
      }
    }
    
    // 调用添加线索API
    const response = await api.post('/clues', requestData)
    
    if (response.data.code === 1) {
      ElMessage.success('添加线索成功')
      dialogFormVisible.value = false
      loadClueList()
    } else {
      ElMessage.error(response.data.msg || '添加线索失败')
    }
  } catch (error) {
    console.error('添加线索出错:', error)
    if (error.name !== 'Error') {
      ElMessage.error('表单验证失败，请检查输入')
    } else {
      ElMessage.error('添加线索失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 提交跟进记录
const submitFollow = async () => {
  try {
    // 表单验证
    const valid = await followFormRef.value.validate()
    if (!valid) {
      return
    }
    
    loading.value = true

    // 构建请求数据
    const requestData = {
      id: followForm.id,
      record: followForm.record,
      status: 2, // 跟进中
      nextTime: followForm.nextTime || null,
      intentionSubject: followForm.intentionSubject,
      intentionLevel: followForm.intentionLevel
    }
    
    // 调用跟进线索接口
    const response = await api.put('/clues', requestData)
    
    if (response.data.code === 1) {
      ElMessage.success('跟进记录提交成功')
      handleFollowDialogClose()
      loadClueList()
      
      // 如果当前正在查看该线索的详情，也需要更新详情
      if (detailDialogVisible.value && detailClue.id === followForm.id) {
        await viewClue({ id: followForm.id })
      }
    } else {
      ElMessage.error(response.data.msg || '跟进记录提交失败')
    }
  } catch (error) {
    console.error('提交跟进记录出错:', error)
    if (error.name !== 'Error') {
      ElMessage.error('表单验证失败，请检查输入')
    } else {
      ElMessage.error('跟进记录提交失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

const handleFileChange = (file, fileList) => {
  // 处理文件变化
  console.log('文件已选择:', file)
}

const submitImport = () => {
  // 模拟导入
  setTimeout(() => {
    ElMessage.success('线索导入成功')
    importDialogVisible.value = false
    loadClueList()
  }, 1000)
}

// 计算属性

const getStatusClass = (status) => {
  const classMap = {
    'pending_allocation': 'status-pending',
    'pending_follow_up': 'status-follow',
    'following': 'status-following',
    'fake': 'status-fake',
    'converted': 'status-converted'
  }
  return classMap[status] || ''
}
</script>

<style scoped>
.clue-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  width: 100%;
  box-sizing: border-box;
}

/* 搜索筛选区域 */
.search-filter {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.filter-row {
  display: flex;
  gap: 15px;
  align-items: end;
  flex-wrap: wrap;
}

.search-input {
  width: 250px;
}

.search-select {
  width: 200px;
}

/* 工具栏 */
.toolbar {
  display: flex;
  gap: 10px;
}

/* 表格样式 */
.clue-table-wrapper {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow-x: auto;
  width: 100%;
  box-sizing: border-box;
}

/* 分页 */
.pagination {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 10px;
  flex-wrap: wrap;
  gap: 10px;
  width: 100%;
}

.total-info {
  color: #606266;
}

.page-size-select {
  display: flex;
  align-items: center;
  gap: 5px;
}

.page-size-select-inner {
  width: auto;
}

.jump-to {
  display: flex;
  align-items: center;
  gap: 5px;
}

.jump-input {
  width: 80px;
}

/* 状态标签样式 */
.status-pending {
  color: #e6a23c;
  font-weight: 500;
}

.status-follow {
  color: #67c23a;
  font-weight: 500;
}

.status-following {
  color: #409eff;
  font-weight: 500;
}

.status-fake {
  color: #909399;
  font-weight: 500;
}

.status-converted {
  color: #f56c6c;
  font-weight: 500;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .filter-row {
    flex-wrap: wrap;
  }
  
  .search-input,
  .search-select {
    width: calc(50% - 10px);
    min-width: 200px;
  }
}

@media (max-width: 768px) {
  .search-input,
  .search-select {
    width: 100%;
  }
  
  .toolbar {
    flex-wrap: wrap;
  }
}
</style>